<?php

namespace app\admin\model;

use app\admin\common\Common;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class KmModel extends Model
{
    public static function delkm($data){
        try {
            $km = Db::name('km')->delete($data['id']);
        } catch (PDOException $e) {
             return Common::result(400,$e->getMessage());
        } catch (Exception $e) {
             return Common::result(400,$e->getMessage());
        }
        if ($km>0){
            return Common::result(200,"删除成功");
        }else{
            return Common::result(400,'删除失败');
        }
    }

    public static function addkm($data){
        try {
            $app = Db::name('app')->where('appid', $data['appid'])->find();
        } catch (DataNotFoundException $e) {
             return Common::result(400,$e->getMessage());
        } catch (ModelNotFoundException $e) {
             return Common::result(400,$e->getMessage());
        } catch (DbException $e) {
             return Common::result(400,$e->getMessage());
        }
        if ($app == null){
            return Common::result(400,'app不存在');
        }else {
            for ($a = 0;$a<$data['generatenum'];$a++){
                $km = Common::getchar($data['kmlength']);
                $adddata = [
                    'km' => $km,
                    'exp' => $data['exp'],
                    'money' => $data['money'],
                    'vip' => $data['vip'],
                    'appid' => $data['appid'],
                    'creattime' => time(),
                ];
                Db::name('km')->insert($adddata);
            }
            return Common::result(200,"生成成功");
        }
    }

    public static function searchkm($data){
        try {
            $sql = Db::name('km')
                ->alias('k')
                ->where('km', $data['searchkm'])
                ->join('app a', 'a.appid = k.appid')
                ->field('k.*,FROM_UNIXTIME(k.creattime,"%Y-%m-%d %T") as time,a.appname')
                ->select();
        } catch (DataNotFoundException $e) {
             return Common::result(400,$e->getMessage());
        } catch (ModelNotFoundException $e) {
             return Common::result(400,$e->getMessage());
        } catch (DbException $e) {
             return Common::result(400,$e->getMessage());
        }
        if (sizeof($sql) == 0){
            return Common::result(400,"暂无查询到数据");
        }else{
            return Common::result(200,"查询成功",$sql);
        }
    }

}